package com.dhcc.bpm.common.utils;

import org.apache.tomcat.util.http.fileupload.FileItemIterator;
import org.apache.tomcat.util.http.fileupload.FileItemStream;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.*;

public class FilEUploadUtils {
    private static final Logger log = LoggerFactory.getLogger(FilEUploadUtils.class);

    public static String getFileContentFromRequest(HttpServletRequest request) {
        FileItemStream itemStream = null;
        BufferedInputStream inputStream = null;
        try {
            request.setCharacterEncoding("utf-8");
            if (ServletFileUpload.isMultipartContent(request)) {
                DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();// 创建该对象
                ServletFileUpload fileUpload = new ServletFileUpload(diskFileItemFactory);// 创建该对象
                FileItemIterator itemIterator = fileUpload.getItemIterator(request);// 解析request 请求,并返回FileItemIterator集合
                StringBuffer fileContent = new StringBuffer();
                while (itemIterator.hasNext()) {
                    itemStream = itemIterator.next();//从集合中获得一个文件流
                    if (!itemStream.isFormField() && itemStream.getName().length() > 0) {    //过滤掉表单中非文件
                        try (InputStream in = itemStream.openStream()) {
                            inputStream = new BufferedInputStream(in);//获得文件输入流
                            inputStream.mark(in.available() + 1);
                            //判断上传的文件的编码格式 支持 UTF-8 和 ANSI两种类型
                            String charsetName = getFileCharsetName(inputStream);

                            try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, charsetName))) {
                                String lineTxt = null;
                                while ((lineTxt = bufferedReader.readLine()) != null) {
                                    fileContent.append(lineTxt + "\r");
                                }
                            } catch (IOException e) {
                                log.error("异常信息：{}", e);
                            }
                        }catch (IOException e) {
                            log.error("异常信息：{}", e);
                        }
                    }
                }
                return fileContent.toString();
            }
        } catch (Exception e) {
            log.error("异常信息：{}", e);
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    log.error("异常信息：{}", e);
                }
            }
        }
        return null;
    }

    //判断上传的文件的编码格式 支持 UTF-8 和 ANSI两种类型
    private static String getFileCharsetName(InputStream inputStream) throws IOException {
        String charsetName = "GBK";
        byte[] typeByte = new byte[3];

        inputStream.read(typeByte);
        if (typeByte[0] == -17 && typeByte[1] == -69 && typeByte[2] == -65) {
            charsetName = "UTF-8";
        } else {
            charsetName = "GBK";
        }
        inputStream.reset();
        return charsetName;
    }


    public static String convertStreamToString(HttpServletRequest request){
        StringBuilder sb = null;
        MultipartHttpServletRequest params =((MultipartHttpServletRequest) request);
        MultipartFile file  = ((MultipartHttpServletRequest) request).getFiles("file").get(0);
        try (InputStream inputStream = file.getInputStream()) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            sb = new StringBuilder();

            String line = null;
            try {
                while ((line = reader.readLine()) != null) {
                    sb.append(line);
                }
            } catch (IOException e) {
               log.error("读取文件异常：{}", e);
            } finally {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    log.error("读取文件异常：{}", e);
                }
            }
        }catch (IOException e) {
            log.error("读取文件异常：{}", e);
        }

        return sb.toString();
    }
}